<template>
  <div v-if="$slots.default" class="x-landing-select">
    <slot />
  </div>
  <x-drawer
    v-model:visible="drawerVisible"
    :header-style="tabs.length > 1 ? 'padding-bottom: 0;' : ''"
    width="80%"
    @update:show="handleCancel"
  >
    <template #header>
      <n-space>
        <n-text>{{ drawerTitle }}</n-text>
        <n-text v-if="drawerTitleDesc" style="font-size: 14px; font-weight: normal; color: #999">
          {{ drawerTitleDesc }}
        </n-text>
      </n-space>
    </template>
    <n-spin :show="loading">
      <x-form ref="filterFormRef" v-model:model="formData" size="small" label-placement="left" inline wrap>
        <template v-if="currentTab === 'pages'">
          <n-form-item label="页面名称" path="title">
            <n-input v-model:value="formData.title" clearable placeholder="请输入内容" />
          </n-form-item>
          <n-form-item label="创建账号" path="creatorId">
            <n-select
              v-model:value="formData.creatorId"
              :options="creator.options"
              clearable
              filterable
              placeholder="请输入姓名查询"
            />
          </n-form-item>
          <n-form-item label="创建时间" path="time">
            <n-date-picker
              v-model:value="formData.time"
              :is-date-disabled="disablePreviousDate"
              type="daterange"
              close-on-select
              clearable
              placeholder="请选择日期范围"
            />
          </n-form-item>
        </template>

        <template v-if="currentTab === 'product'">
          <n-form-item>
            <n-input-group>
              <n-select
                v-model:value="formData.keywordType"
                :options="keywordTypeList"
                style="min-width: 100px; width: 100px"
              />
              <n-input v-model:value="formData.keyword" clearable placeholder="请输入内容" />
            </n-input-group>
          </n-form-item>
          <n-form-item label="商品类目" path="categoryId">
            <x-product-category v-model:value="formData.categoryId" />
          </n-form-item>
          <n-form-item label="商品品牌">
            <n-select
              v-model:value="formData.productBrand"
              :options="brand.options"
              :loading="brand.loading"
              placeholder="请输入关键字搜索品牌"
              multiple
              filterable
              clearable
              remote
              @search="handleSearchBrand"
            />
          </n-form-item>
          <n-form-item label="当前价">
            <n-input v-model:value="formData.price" separator="-" pair clearable :placeholder="['最低价', '最高价']" />
          </n-form-item>
          <n-form-item>
            <n-input-group>
              <n-select
                v-model:value="formData.storeType"
                :options="dictionary['STORE_SEARCH_TYPE_LIST']"
                style="min-width: 100px; width: 100px"
              />
              <n-input
                v-if="formData.storeType === 'storeId'"
                v-model:value="formData.storeId"
                clearable
                placeholder="请输入内容"
              />
              <n-input
                v-if="formData.storeType === 'storeName'"
                v-model:value="formData.storeName"
                clearable
                placeholder="请输入内容"
              />
            </n-input-group>
          </n-form-item>
        </template>
        <template v-if="currentTab === 'coupon'">
          <n-form-item label="选择店铺" path="keyword">
            <n-select
              v-model:value="formData.keyword"
              :options="storeSelect.options"
              :loading="storeSelect.loading"
              :clear-filter-after-select="false"
              filterable
              clearable
              remote
              placeholder="请输入店铺ID或者名称查询"
              style="width: 300px"
              @search="handleStoreSearch"
              @update:value="handleStoreChange"
            />
          </n-form-item>
          <n-form-item label="优惠券名称" path="couponName">
            <n-input v-model:value="formData.couponName" clearable placeholder="请输入内容" />
          </n-form-item>
          <n-form-item label="可用商品" path="productId">
            <n-input v-model:value="formData.productId" clearable placeholder="请输入产品ID" />
          </n-form-item>
        </template>
        <template v-if="currentTab === 'subsidy'">
          <n-form-item>
            <n-input-group>
              <n-select
                v-model:value="formData.keywordType"
                :options="keywordTypeList"
                style="min-width: 120px; width: 120px"
              />
              <n-input
                v-model:value="formData.keyword"
                placeholder="请输入内容"
                clearable
                @keyup.enter="immediate = true"
              />
            </n-input-group>
          </n-form-item>
          <n-form-item label="活动名称" path="activityName">
            <n-input v-model:value="formData.activityName" clearable placeholder="请输入内容" />
          </n-form-item>
        </template>

        <n-form-item>
          <n-space align="center">
            <x-button type="primary" @click="submitFormFilter">查询</x-button>
            <x-button @click="resetForm">重置</x-button>
            <n-checkbox v-model:checked="selectSwitch" @update:checked="handleChangeSelectSwitch">
              仅查看已选中
            </n-checkbox>
          </n-space>
        </n-form-item>
      </x-form>
      <x-data-table
        v-if="rulesRequiredParams"
        ref="tableElRef"
        v-model:immediate="immediate"
        v-model:checked-row-keys="checkedRowKeys"
        :params="dataTableParams"
        :columns="columns"
        :row-key="(row) => row.id"
        :toolbar="false"
        @update:checked-row-keys="handleCheck"
      />
      <div v-else class="empty">
        <n-empty description="请先选择店铺" />
      </div>
    </n-spin>
    <template v-if="multiple && !readonly" #footer>
      <n-space align="center">
        <n-text>已选择({{ checkedRowKeys?.length || 0 }})</n-text>
        <x-button type="primary" ghost @click="handleCancel">取消</x-button>
        <x-button :loading="loading" type="primary" @click="submitForm">确定</x-button>
      </n-space>
    </template>
  </x-drawer>
</template>

<script lang="ts">
  import { computed, defineComponent, reactive, toRefs, watch, ref, h, VNode } from 'vue'
  import {
    NImage,
    NTag,
    NSpin,
    NSpace,
    NText,
    NEllipsis,
    NInputGroup,
    NInput,
    NDivider,
    NSelect,
    NFormItem,
    NCheckbox,
    NDatePicker,
    NEmpty,
    useMessage
  } from 'naive-ui'
  import { XForm, XDrawer, XButton, XDataTable, XProductCategory } from '@/components'
  import { useStore } from '@/store'
  import { useDictionary } from '@/hooks'
  import { formatDate, formatCdn } from '@/utils'
  import { useRouter } from 'vue-router'
  import { ProductListRow } from '@/api/model/productModel'

  export default defineComponent({
    name: 'XLandingSelect',
    components: {
      NSpin,
      NSpace,
      NInputGroup,
      NInput,
      NSelect,
      NText,
      NFormItem,
      NDatePicker,
      NCheckbox,
      NEmpty,
      XForm,
      XDrawer,
      XButton,
      XDataTable,
      XProductCategory
    },
    props: {
      tabs: {
        type: Array,
        default: () => ['product']
      },
      // 默认选中值
      defaultValue: {
        type: String,
        default: null
      },
      // 过滤不可选择的值
      filters: {
        type: Array,
        default: () => []
      },
      visible: {
        type: Boolean,
        default: false
      },
      // 外部扩展查询参数
      defaultFormData: {
        type: Object,
        default: () => {}
      },
      // 外部扩展查询参数
      params: {
        type: Object,
        default: () => {}
      },
      value: {
        type: [String, Number, Array],
        default: null
      },
      // 只读
      readonly: {
        type: Boolean,
        default: false
      },
      multiple: {
        type: Boolean,
        default: false
      },
      // 多选时用户最多可以选择的项目数，为 0 则不限制
      multipleLimit: {
        type: Number,
        default: 0
      },
      // 标题
      title: {
        type: String,
        default: ''
      },
      // 标题后面的描述文案
      titleDesc: {
        type: String,
        default: ''
      },
      // 所需的必填参
      requiredParams: {
        type: Array,
        default: () => null
      },
      appId: {
        type: String,
        default: ''
      },
      companyName: {
        type: String,
        default: ''
      }
    },
    emits: ['update', 'update:visible', 'update:value', 'close', 'submit'],
    setup($props, { emit: $emit }) {
      const $message = useMessage()
      const $store = useStore()
      const $router = useRouter()
      const $dictionary = useDictionary()
      $dictionary.get([
        'PRODUCTION_ACTION_TYPE',
        'PRODUCT_EXAMINE_STATUS',
        'PRODUCT_DISPLAY_STATUS',
        'GIFT_ACTIVITY_STATUS',
        'STORE_COUPON_STATUS',
        'STORE_SEARCH_TYPE_LIST',
        'STORE_COUPON_SCENE',
        'PRODUCT_TYPE'
      ])
      const filterFormRef: any = ref(null)
      // 初始化查询类型
      const initKeywordType = (value: any) => {
        switch (value) {
          case 'product':
            return 1
          case 'coupon':
          case 'subsidy':
            return 'storeId'
          default:
            return null
        }
      }

      const $state: any = reactive({
        ...toRefs($props),
        drawerVisible: $props.visible,
        checkedRowKeys: $props.multiple ? $props.value : [],
        currentTab: $props.tabs[0], // pages | product | advertising
        // 店铺选择查询
        storeSelect: {
          options: [],
          loading: false
        },
        tabList: [
          {
            label: '微页面',
            value: 'pages',
            desc: '（仅支持选择已发布的微页面，不支持选择当前页面）'
          },
          {
            label: '商品',
            value: 'product',
            desc: '（仅支持选择在售中/显示的普通商品和视频号商品）'
          },
          {
            label: '领券中心',
            value: 'coupon',
            desc: '（仅支持选择已生效的领券中心券）'
          },
          {
            label: '活动补贴',
            value: 'subsidy',
            desc: '（仅支持选择进行中的活动）'
          }
        ],
        drawerTitle: computed(() =>
          $state.title
            ? $state.title
            : $state.tabList.find((item: { value: string }) => item.value === $state.currentTab)?.label
        ),
        drawerTitleDesc: computed(() =>
          $state.titleDesc
            ? $state.titleDesc
            : $state.tabList.find((item: { value: string }) => item.value === $state.currentTab)?.desc
        ),
        // 是否仅看已选中的数据
        selectSwitch: $props.readonly,
        formData: {
          keywordType: initKeywordType($props.tabs[0]),
          keyword: null,
          title: null,
          time: null,
          creatorId: null,
          brandIdList: [],
          categoryId: null,
          productBrand: [],
          price: null,
          pageStatus: 1,
          storeId: null,
          storeName: null,
          activityName: null,
          couponName: null,
          couponScene: 2,
          productId: null,
          order: null,
          sort: null,
          storeType: 'storeId',
          productIdList: [],
          pageIdList: [],
          activityIdList: [],
          couponIdList: [],
          appId: $props.appId,
          companyName: $props.companyName,
          ...($props.defaultFormData || {})
        },
        loading: false,
        keywordTypeList: computed(() => {
          let list
          switch ($state.currentTab) {
            case 'product':
              list = [
                {
                  label: '商品名称',
                  value: 1
                },
                {
                  label: '产品ID',
                  value: 2
                },
                {
                  label: '编码',
                  value: 3
                }
              ]
              break
            case 'coupon':
            case 'subsidy':
              list = [
                {
                  label: '店铺ID',
                  value: 'storeId'
                },
                {
                  label: '店铺名称',
                  value: 'storeName'
                }
              ]
              break
          }
          return list
        }),
        // 品牌数据
        brand: {
          loading: false,
          options: []
        },
        // 创建账号
        creator: {
          loading: false,
          options: []
        },
        // 选中的第一个时间
        oneDate: 0,
        disablePreviousDate(ts: number, type: string, range: number[]) {
          if (type === 'start' && range !== null) {
            $state.oneDate = range[0]
          }
          if ($state.oneDate) {
            const t = $state.oneDate - ts
            // 只能选择30天范围的数据
            const d = t / (1000 * 60 * 60 * 24)
            if (d > 90 || d < -90) {
              return true
            }
          }
          return ts > Date.now()
        },
        dataTableParams: computed(() => {
          const formData = $state.formData
          const params = {}
          let actions
          switch ($state.currentTab) {
            case 'pages':
              actions = 'marketing/getPagesList'
              Object.assign(params, {
                title: formData.title,
                creatorId: formData.creatorId,
                pageType: formData.pageType,
                appId: $state.appId,
                companyName: $props.companyName
              })
              // 仅查看已选中数据
              if ($state.selectSwitch && formData.pageIdList?.length) {
                Object.assign(params, {
                  pageIdList: formData.pageIdList
                })
              }
              if ($state.formData.time) {
                Object.assign(params, {
                  startDate: formatDate(formData.time[0]),
                  endDate: formatDate(formData.time[1])
                })
              }
              break
            case 'product':
              actions = 'product/productList'
              Object.assign(params, {
                keywordType: formData.keywordType,
                keyword: formData.keyword,
                categoryId: formData.categoryId,
                productBrand: formData.productBrand,
                storeId: formData.storeType === 'storeId' ? formData.storeId : null,
                storeName: formData.storeType === 'storeName' ? formData.storeName : null,
                // 商品类型1-普通商品；2-投放商品；3-视频号商品
                productTypeList: [1, 3],
                // 商品是否显示 1-显示；0-不显示
                displayStatus: 1,
                //  0-线上商品；1-审核中商品；2-草稿箱；3-回收站;
                productSelect: 0,
                // 0-全部 1-在售 2-已售罄 3-已下架；4-审核中；5-已驳回；6-已通过;
                tagsType: 1,
                appId: $state.appId,
                companyName: $props.companyName
              })
              if (formData.price) {
                Object.assign(params, {
                  lowPrice: formData.price[0],
                  upPrice: formData.price[1]
                })
              }
              // 仅查看已选中数据
              if ($state.selectSwitch && formData.productIdList?.length) {
                Object.assign(params, {
                  productIdList: formData.productIdList
                })
              }
              break
            case 'coupon':
              actions = 'marketing/getCouponListSearch'
              Object.assign(params, {
                couponName: formData.couponName,
                productId: formData.productId,
                order: formData.order,
                sort: formData.sort,
                couponScene: formData.couponScene,
                [formData.keywordType]: formData.keyword,
                appId: $state.appId,
                companyName: $props.companyName
              })
              // 仅查看已选中数据
              if ($state.selectSwitch && formData.couponIdList?.length) {
                Object.assign(params, {
                  couponIdList: formData.couponIdList
                })
              }
              break
            case 'subsidy':
              actions = 'marketing/getSubsidyList'
              Object.assign(params, {
                activityName: formData.activityName,
                [formData.keywordType]: formData.keyword,
                appId: $props.appId,
                companyName: $props.companyName
              })
              // 仅查看已选中数据
              if ($state.selectSwitch && formData.activityIdList?.length) {
                Object.assign(params, {
                  activityIdList: formData.activityIdList
                })
              }
              break
          }
          Object.assign(params, $state.params || {})
          return {
            actions,
            data: params
          }
        }),
        immediate: true,
        // 校验必要参数是否已经具备
        rulesRequiredParams: computed(() => {
          if ($state.readonly) return true
          if ($state.requiredParams?.length) {
            let is = false
            $state.requiredParams.forEach((key: string) => {
              console.log(111, key, $state.dataTableParams.data[key])
              if ($state.dataTableParams.data[key]) {
                is = true
              }
            })
            return is
          } else {
            return true
          }
        }),
        // 字典
        dictionary: computed(() => $store.getters.dictionary),
        columns: computed(() => {
          let columns
          switch ($state.currentTab) {
            case 'pages':
              columns = [...$state.columnsA]
              break
            case 'product':
              columns = [...$state.columnsB]
              break
            case 'coupon':
              columns = [...$state.columnsC]
              break
            case 'subsidy':
              columns = [...$state.columnsD]
              break
            default:
              columns = [...$state.columnsA]
              break
          }
          // 多选
          if (!$props.readonly && $props.multiple && !columns.some((s: { type: string }) => s.type === 'selection')) {
            columns.unshift({
              type: 'selection'
            })
          }
          // 单选
          if (!$props.readonly && !$props.multiple && !columns.some((s: { type: string }) => s.type === 'tools')) {
            columns.push({
              title: '操作',
              align: 'center',
              type: 'tools',
              render(row: { id: number | string }): VNode {
                return h(
                  XButton,
                  {
                    text: true,
                    type: 'primary',
                    disabled: $state.filters?.some((item: string | number) => String(item) === String(row.id)),
                    onClick: () => {
                      $emit('update:value', row.id, row, $state.currentTab)
                      handleCancel()
                    }
                  },
                  () => '选择'
                )
              }
            })
          }
          return columns
        }),
        // 微页面
        columnsA: [
          {
            title: '页面名称',
            render(row: { id: number; title: string; pageStatus: number; pageAggregation: number }): VNode {
              return h(
                NSpace,
                {
                  vertical: true,
                  size: 1
                },
                () => [
                  h(
                    NEllipsis,
                    {
                      style: 'max-width: 300px;'
                    },
                    () => row.title
                  ),
                  h(NSpace, {}, () => [
                    h(NText, {}, () => `页面ID：${row.id}`),
                    row.pageStatus
                      ? h(
                          NTag,
                          {
                            type: 'info'
                          },
                          () => '商城主页'
                        )
                      : null
                  ])
                ]
              )
            }
          },
          {
            title: '商品数',
            align: 'center',
            key: 'productNum'
          },
          {
            title: '访客数/浏览量',
            align: 'center',
            render(row: { pageUv: number; pagePv: number }): VNode {
              return h(NSpace, { size: 2, justify: 'center' }, () => [
                h(NText, {}, () => `${row.pageUv}`),
                h(NDivider, { vertical: true }),
                h(NText, {}, () => `${row.pagePv}`)
              ])
            }
          },
          {
            title: '商品访客数/商品浏览量',
            align: 'center',
            render(row: { productUv: number; productPv: number }): VNode {
              return h(NSpace, { size: 2, justify: 'center' }, () => [
                h(NText, {}, () => `${row.productUv}`),
                h(NDivider, { vertical: true }),
                h(NText, {}, () => `${row.productPv}`)
              ])
            }
          },
          {
            title: '创建时间',
            align: 'center',
            key: 'createdAt'
          },
          {
            title: '最后修改时间',
            align: 'center',
            key: 'updateAt'
          },
          {
            title: '创建账号',
            align: 'center',
            render(row: { creatorName: string; creatorPhone: string }): VNode {
              return h(NSpace, { size: 1, vertical: true }, () => [
                h(NText, {}, () => `${row.creatorName}`),
                h(NText, {}, () => `${row.creatorPhone}`)
              ])
            }
          },
          {
            title: '最后修改账号',
            align: 'center',
            render(row: { updateName: string; updatePhone: string }): VNode {
              return h(NSpace, { size: 1, vertical: true }, () => [
                h(NText, {}, () => `${row.updateName}`),
                h(NText, {}, () => `${row.updatePhone}`)
              ])
            }
          }
        ],
        // 自营商品
        columnsB: [
          {
            title: '商品',
            width: 350,
            render(row: {
              productTitle: string
              productBrandName: string
              productNum: string
              productNo: string
              productMainPic: string
            }): VNode {
              return h(NSpace, null, () => [
                h(NImage, {
                  src: formatCdn(row.productMainPic),
                  previewSrc: row.productMainPic,
                  width: 80,
                  height: 80
                }),
                h(
                  NSpace,
                  {
                    vertical: true,
                    size: 1
                  },
                  () => [
                    h(
                      NEllipsis,
                      {
                        style: 'max-width: 290px;'
                      },
                      () => row.productTitle
                    ),
                    h(NText, {}, () => `品牌：${row.productBrandName || '无'}`),
                    h(NText, {}, () => `编码：${row.productNum || '-'}`),
                    h(NText, {}, () => `产品ID：${row.productNo || '-'}`)
                  ]
                )
              ])
            }
          },
          {
            title: '店铺信息',
            width: 120,
            render(row: { storeId: number; storeName: string }): VNode {
              return h(NSpace, { size: 2, vertical: true }, () => [
                h(NText, {}, () => `店铺：${row.storeName}`),
                h(NText, {}, () => `店铺ID：${row.storeId}`)
              ])
            }
          },
          {
            title: '当前价格',
            align: 'right',
            key: 'groupPrice',
            render(row: { groupPrice: number }): VNode {
              return h(NText, {}, () => `￥${row.groupPrice}`)
            }
          },
          {
            title: '访问量',
            render(row: { productUv: number; productPv: number }): VNode {
              return h(
                NSpace,
                {
                  vertical: true
                },
                () => [h(NText, {}, () => `访客数：${row.productUv}`), h(NText, {}, () => `浏览量：${row.productPv}`)]
              )
            }
          },
          {
            title: '销量',
            align: 'right',
            key: 'salesNum'
          },
          {
            title: '排序',
            align: 'right',
            key: 'mallProductSort'
          },
          {
            title: '编辑账号',
            key: 'productStatus',
            align: 'center',
            ellipsis: {
              tooltip: true
            },
            render(row: ProductListRow): VNode {
              return h(
                NSpace,
                {
                  vertical: true,
                  size: 3
                },
                () => [h(NText, {}, () => row.updatedName || '-'), h(NText, {}, () => row.updatedMobile || '-')]
              )
            }
          },
          {
            title: '创建时间',
            align: 'center',
            key: 'createdTime',
            width: 100
          }
        ],
        // 优惠券
        columnsC: [
          {
            title: '店铺信息',
            render(row: { storeId: number; storeName: string }): VNode {
              return h(NSpace, { size: 2, vertical: true }, () => [
                h(NText, {}, () => `店铺名称：${row.storeName}`),
                h(NText, {}, () => `店铺ID：${row.storeId}`)
              ])
            }
          },
          {
            title: '优惠劵信息',
            render(row: { id: number; couponName: string }): VNode {
              return h(NSpace, { size: 2, vertical: true }, () => [
                h(NText, {}, () => `券名称：${row.couponName}`),
                h(NText, {}, () => `券ID：${row.id}`)
              ])
            }
          },
          {
            title: '类型',
            key: 'validityType',
            render(row: { validityType: number }): VNode {
              return h(NText, {}, () => $dictionary.find(row.validityType, 'STORE_COUPON_SCENE'))
            }
          },
          {
            title: '可用商品',
            render(row: { suitableType: number }): VNode | string {
              if (row.suitableType === 3) {
                return '全部商品'
              } else {
                return '部分商品'
              }
            }
          },
          {
            key: 'balanceCoupons',
            title: '剩余/总数',
            render(row: { balanceCoupons: number; maxCoupons: number }): string {
              return `${row.balanceCoupons}/${row.maxCoupons}`
            }
          },
          {
            title: '有效期',
            render(row: {
              availableStartedAt: string
              availableEndedAt: string
              validityType: number
              validityDays: string
              waitDays: string
            }): string {
              let validDateStr = `${row.availableStartedAt} 至 ${row.availableEndedAt}`
              if (row.validityType === 2) {
                validDateStr = `领取后${row.validityDays}天内有效`
              } else if (row.validityType === 3) {
                validDateStr = `领券后第${row.waitDays}日起${row.validityDays}天内有效`
              }
              return validDateStr
            }
          },
          {
            title: '状态',
            key: 'couponStatus',
            render(row: { couponStatus: number }): VNode {
              return h(
                NTag,
                {
                  size: 'small',
                  type: ['', 'success', 'error'][row.couponStatus]
                },
                () => $dictionary.find(row.couponStatus, 'STORE_COUPON_STATUS')
              )
            }
          }
        ],
        // 官方补贴
        columnsD: [
          {
            title: '店铺信息',
            render(row: { storeId: number; storeName: string }): VNode {
              return h(NSpace, { size: 2, vertical: true }, () => [
                h(NText, {}, () => `店铺名称：${row.storeName}`),
                h(NText, {}, () => `店铺ID：${row.storeId}`)
              ])
            }
          },
          {
            title: '编码',
            key: 'id'
          },
          {
            title: '活动名称',
            key: 'activityName'
          },
          {
            title: '开始时间',
            key: 'startAt'
          },
          {
            title: '结束时间',
            key: 'endAt'
          },
          {
            title: '状态',
            width: 100,
            key: 'activityStatus',
            render(row: { activityStatus: number }): VNode {
              return h(
                NTag,
                {
                  size: 'small',
                  type: row.activityStatus ? 'info' : 'success'
                },
                () => $dictionary.find(row.activityStatus, 'GIFT_ACTIVITY_STATUS')
              )
            }
          }
        ]
      })

      // 店铺查询
      const handleStoreSearch = (val: string) => {
        const payload: any = {
          timeType: 1,
          auditedType: 0,
          storeStatus: 1,
          applymentState: 'FINISH',
          deliveryPluginStatus: 0,
          storeId: null,
          storeName: null,
          channelCompanyName: $props.companyName,
          pageNum: 1,
          pageSize: 1000
        }
        if (/^\d+$/.test(val)) {
          payload.storeId = val
        } else {
          payload.storeName = val || ''
        }
        console.log(payload, 111111111)
        $state.storeSelect.loading = true
        $store
          .dispatch('shop/getShopList', payload)
          .then((res) => {
            const list = res.data || []
            const options = list.map((item: { storeName: string; storeId: number }) => {
              return {
                ...item,
                label: item.storeName,
                value: item.storeId
              }
            })
            $state.storeSelect = {
              loading: false,
              options
            }
          })
          .catch(() => {
            $state.storeSelect.loading = false
          })
      }
      handleStoreSearch('')
      // 选择店铺
      const handleStoreChange = () => {
        $state.checkedRowKeys = []
        $state.formData.keywordType = 'storeId'
        submitFormFilter()
      }

      // 取消操作
      const handleCancel = () => {
        $state.drawerVisible = false
        $state.loading = false
        $emit('update:visible', false)
        $emit('close')
      }

      // 搜索品牌
      const handleSearchBrand = (key = '') => {
        $state.brand.loading = true
        $store
          .dispatch('product/getProductBrandList', {
            pageNum: 1,
            applymentStatus: 1,
            keyword: key
          })
          .then((res) => {
            $state.brand.options = res.data || []
            $state.brand.loading = false
          })
          .catch(() => {
            $state.brand.loading = false
          })
      }

      // 创建账号
      $store.dispatch('marketing/getPagesCreatorList').then((res) => {
        $state.creator.options = res.data?.map(
          (item: { accountName: string; accountMobile: string; accountId: number }) => ({
            label: `${item.accountName}（${item.accountMobile}）`,
            value: item.accountId
          })
        )
      })

      // 切换tab
      const handleChangeTabs = () => {}

      // 重置
      const resetForm = () => {
        filterFormRef.value && filterFormRef.value.resetFields()
        $state.formData.keywordType = initKeywordType($state.currentTab)
        $state.immediate = true
      }

      // 日期选项值变化时
      const handleChangePicker = (val: number[]) => {
        $state.timeCurrent = null
        if (val) {
          $state.oneDate = 0
        }
      }

      // 查询
      const submitFormFilter = () => {
        $state.immediate = true
      }

      // 选中
      const handleCheck = (ids: string[] | number[]) => {
        // $emit('update:value', ids)
        $state.checkedRowKeys = ids
      }

      // 确定保存
      const submitForm = () => {
        const value = $state.checkedRowKeys
        if ($props.multipleLimit) {
          const msg = `最多只能选择${$props.multipleLimit}项`
          if ($props.multiple && value?.length > $props.multipleLimit) {
            return $message.warning(msg)
          }
        }
        $emit('update:value', value)
        handleCancel()
      }

      // 新建非卖品跳转
      const handleToGift = () => {
        $router.push({
          name: 'ProductGiftList'
        })
      }

      // 仅看已选数据
      const handleChangeSelectSwitch = () => {
        let key = ''
        switch ($state.currentTab) {
          case 'pages':
            key = 'pageIdList'
            break
          case 'product':
            key = 'productIdList'
            break
          case 'coupon':
            key = 'couponIdList'
            break
          case 'subsidy':
            key = 'activityIdList'
            break
        }
        const value = $state.multiple ? $state.checkedRowKeys || [] : [$props.value || '']
        $state.formData[key] = $state.selectSwitch ? value : []
        $state.immediate = true
      }

      if ($state.readonly) {
        handleChangeSelectSwitch()
      }

      // watch
      watch(
        () => $props.visible,
        (value: boolean) => {
          $state.drawerVisible = value
          if (value) {
            resetForm()
            $state.checkedRowKeys = $props.multiple ? $props.value : []
            // 先获取第一页数据
            // 品牌
            handleSearchBrand()
          } else {
            $state.selectSwitch = false
          }
        },
        {
          immediate: true
        }
      )
      watch(
        () => $props.value,
        (value: any) => {
          $state.checkedRowKeys = $props.multiple ? value : []
        }
      )
      watch(
        () => $props.tabs,
        (value: any) => {
          $state.currentTab = value[0]
        }
      )

      return {
        ...toRefs($state),
        filterFormRef,
        resetForm,
        submitFormFilter,
        handleCancel,
        submitForm,
        handleSearchBrand,
        handleCheck,
        handleChangeTabs,
        handleChangePicker,
        handleToGift,
        handleChangeSelectSwitch,
        handleStoreSearch,
        handleStoreChange
      }
    }
  })
</script>

<style></style>
